var ctx = localStorage.getItem("ctx");
$(function() {
	
	juicer.set({
	    'tag::operationOpen': '-~',
	    'tag::operationClose': '+',
	    'tag::interpolateOpen': '#-',
	    'tag::interpolateClose': '+',
	    'tag::noneencodeOpen': '##-',
	    'tag::noneencodeClose': '+',
	    'tag::commentOpen': '-*',
	    'tag::commentClose': '+'
	});
	
	//显示当前时间
	$(".driverFirstDate").val(getNowFormatDate());
	$(".driverEndDate").val(getNowFormatDate());
	$(".registerDate").val(getNowFormatDate());
	
	$(".ulBrand").hide();
	var wholeautype = '';
	
	

//    getCarBrand();
    //车辆类型初始化的时候默认选择第一个车辆品牌的类型
//    getCarModel('33');
   
    //根据选取的省份获取城市和公司
    $(".provinceSelect").on("change", function(){
    	var provinceId = $(this).attr("value");
    	getCity(provinceId);
    	getCompany(provinceId,'');
    });
    
    //根据省份和城市获取公司
    $(".citySelect").on("change", function() {   	
    	var provinceId = $(".provinceSelect").find("option:selected").attr("value");
    	var cityId = $(this).attr("value");
    	getCompany(provinceId,cityId);
    });
    
    //根据车辆品牌查询车辆类型
    $(".carBrandSelect").on("change", function(){
    	var carBrandId = $(this).attr("value");
    	getCarModel(carBrandId);
    });
	
    //根据出租车专车类型显示不同
    $(".authType input").on("change", function() {
    	wholeautype = $(this).attr('value');
    	if($(this).attr('value') == 2) {
    		$(".workLicenseImageWrapdiv").hide();
    		$(".workLicenseNumberTh").hide();
    		$(".workLicenseNumberTd").hide();
    	}
    	else {
    		$(".workLicenseImageWrapdiv").show();
    		$(".workLicenseNumberTh").show();
    		$(".workLicenseNumberTd").show();
    	}
    });
    
    //根据输入选择车辆品牌
    $(".keydowninput").on('keyup', function() {
//    	alert($(this).val());
    	$(".ulBrand").show();
    	var keyval = $(this).val();
    	$.ajax({
    		type: 'POST',
    		url: ctx+'/cartype/v1/brandbykeys',
    		dataType: 'json',
    		data: {
    			keys: keyval
    		},
    		success: function(data) {
    			console.log(data);
    			var ulModels = {};
    			ulModels.list = data;
    			var ulTpl = document.getElementById("liBrandTpl").innerHTML;
    			var ulModelhtml = juicer(ulTpl, ulModels);
    			$(".ulBrand").html(ulModelhtml);
    		}
    	});
    });
    
    $(".ulBrand").on('click', 'li', function() {
//    	alert($(this).attr("data-value"));
    	$(".keydowninput").val($(this).text());
    	$(".keydowninput").attr("data-value", $(this).attr("data-value"));
    	getCarModel($(this).attr("data-value"));
    	$(".ulBrand").hide();
    });
    
    $(document).on("click", function() {
    	$(".ulBrand").hide();
    })
    
    $("#adddriverform").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	driverName: {//姓名
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                    	message: '只能输入汉字或英文姓名'
                    }
                }
            },
            driverTel: {//手机号码
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/,
                    	message: '请输入正确格式手机号码'
                    }
                }
            },
            driverIdCard: {//身份证号
            	validators: {
            		notEmpty: {
            			message: '不能为空'
            		},
            		regexp: {
            			regexp: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            			message: '请输入正确身份证号码'
            		}
            	}
            },
            driverLicNo: {//驾驶证档案编号
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^\d{12}$/,
                    	message: '12位数字'
                    }
                }
            },
            driverCarNo: {//车牌号
            	validators: {
            		notEmpty: {
            			message: '不能为空'
            		},
            		regexp: {
            			regexp: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
            			message: '简称+大写英文字母+5位数字'
            		}
            	}
            },
            vehicleNo: {//车架号
            	validators: {
            		notEmpty: {
            			message: '不能为空'
            		},
            		regexp: {
            			regexp: /^[a-zA-Z0-9]{17}$/,
            			message: '大写字母和数字混合，共17位'
            		}
            	}
            },
            workLicenseNumber: {//从业资格证号
            	validators: {
            		notEmpty: {
            			message: '不能为空'
            		},
            		regexp: {
            			regexp: /^\d{19}$/,
            			message: '19位数字'
            		}
            	}
            }
            
            
        }
	});
    
	//确认添加司机
	$(".driver-add").on("click", function() {
		
		confirmadddriver();
			
 		
	});
    
    //图片上传
    $(".imgInp").change(function(){
    	readURL(this,$(this).attr("data-value"));
    });
    
	
	function uploadImage(srcImage, n) {
		$.ajax({
 			type: 'POST',
 			url: ctx+'/driver/v1/upimage',
 			dataType: 'json',
 			data: {
 				srcImage: srcImage
 			},
 			beforeSend:function(){
 				$(".progress-bar" + n).attr("aria-valuenow", '0');
 				$(".progress-bar" + n).css({width: '20%',color: '#000'});
 				$(".progress-bar" + n).html('上传中..');
 				
// 				$(".upbtn"+n).html('上传中,请耐心等待');
 			},
 			success: function(data) {
// 				$(".upbtn"+n).html('上传成功,点击重新上传');
 				$(".imgBox"+n).attr("data-value",data);
 				$(".progress-bar" + n).attr("aria-valuenow", '100');
 				$(".progress-bar" + n).css({width: '100%'});
 				$(".progress-bar" + n).html('上传成功');
 			}
		});
	}
	
	function readURL(input,n) {
		
//		var fileName=document.getElementById("imgInp"+n).value;  
		var fileName = $(".imgInp"+n).val();
		var suffixIndex=fileName.lastIndexOf(".");  
		var suffix=fileName.substring(suffixIndex+1).toUpperCase();  
		if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){  
			alert("请上传图片");
		}
		else {
			if (input.files && input.files[0]) {
	            var reader = new FileReader();
	            reader.onload = function (e) {
	            	
	                $('#blah'+n).attr('src', e.target.result);
//	                $('.upbtn'+n).attr('data-name','1');
	                uploadImage($('#blah'+n).attr('src'), n);
	            }
	            reader.readAsDataURL(input.files[0]);
	            
	        }
		}
    	
		
    };
	
    
	//获取省份
    function getProvince() {
    	$.ajax({
        	type: 'POST',
    		url: ctx+'/proandcity/v1/pro',
    		dataType: 'json',
    		success: function(data) {
    			
    			var provinceTpl = document.getElementById("provinceSelectTpl").innerHTML;
    			var provincehtml = juicer(provinceTpl, data);
    			var option = "<option value=''>全部</option>";
    			$(".provinceSelect").html(option+provincehtml);
    			
    		}
    	});
    }
    
	
    //根据省份获取城市(可以传空，代表全部)
    function getCity(provinceId) {
    	$.ajax({
        	type: 'POST',
    		url: ctx+'/proandcity/v1/city',
    		dataType: 'json',
    		data: {
    			proviceId: provinceId
    		},
    		success: function(data) {
    			var cityTpl = document.getElementById("citySelectTpl").innerHTML;
    			var cityhtml = juicer(cityTpl, data);
    			$(".citySelect").html(cityhtml);
    			
    		}
    	});
    }
    
    
    //根据省份和城市获取公司(可以传空，代表全部)
    function getCompany(provinceId,cityId) {
    	$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/organization/listId',
    		dataType: 'json',
    		data: {
    			proviceId: provinceId,
    			sysCityId: cityId
    		},
    		success: function(data) {
    			var company = {};
    			company.list = data;
    			var companyTpl = document.getElementById("companySelectTpl").innerHTML;
    			var companyhtml = juicer(companyTpl, company);
    			$(".companySelect").html(companyhtml);
    		}
    	});
    };
    
    //获取车辆品牌
    function getCarBrand() {
    	$.ajax({
    		type: 'POST',
    		url: ctx+'/cartype/v1/brand',
    		dataType: 'json',
    		success: function(data) {
    			var carBrands = {};
    			carBrands.list = data;
    			var carBrandTpl = document.getElementById("carBrandSelectTpl").innerHTML;
    			var carBrandhtml = juicer(carBrandTpl, carBrands);
    			$(".carBrandSelect").html(carBrandhtml);
    		}
    	});
    }
    
    //获取车辆类型
    function getCarModel(carBrandId) {
    	$.ajax({
    		type: 'POST',
    		url: ctx+'/cartype/v1/model',
    		dataType: 'json',
    		data: {
    			id: carBrandId
    		},
    		success: function(data) {
    			var carModels = {};
    			carModels.list = data;
    			var carModelTpl = document.getElementById("carModelSelectTpl").innerHTML;
    			var carModelhtml = juicer(carModelTpl, carModels);
    			$(".carModelSelect").html(carModelhtml);
    		}
    	});
    }
    
	
    //确认添加司机
    function confirmadddriver() {
    	$('#adddriverform').data('bootstrapValidator').validate();  
        if(!$('#adddriverform').data('bootstrapValidator').isValid()){  
            return ;  
        }
        
        var authType = $(".authType input[type='radio']:checked").attr("value");//认证类型
		var driverName = $(".driverName").attr("value");//姓名
		var driverSex = $(".driverSex input[type='radio']:checked").attr("value");//性别
		var driverTel = $(".driverTel").attr("value");//手机号码
		var driverIdCard = $(".driverIdCard").attr("value");//身份证号码
		var firstLicDate = $(".driverFirstDate").val();//初领驾驶证日期
		var endLicDate = $(".driverEndDate").val();//驾驶证截止日期
		var licType = $(".licStyleSelect").find("option:selected").text();//准驾车型
		var licNo = $(".driverLicNo").attr("value");//驾驶证档案编号
		var driverCarNo = $(".carNoDiv input").attr("value");//车牌号
		var vehicleType = $('.keydowninput').val();//车辆品牌
		var vehicleModel = $('.carModelSelect').find('option:selected').html();//车辆型号
		var vehicleNo = $(".vehicleNo").attr("value");//车架号
		var carRegisterDate = $(".registerDate").val();//车辆注册日期
		var carOwnName = $(".carOwnNameSelect").find("option:selected").text();//车辆所有人
		var workLicenseNumber = $(".workLicenseNumber").val();//从业资格证号
		var vehicleColor  = $('.vehicleColor').find('option:selected').html(); //车辆颜色   
		var idCardPositiveImage = $(".imgBox1").attr("data-value");//身份证正面
		var idCardOppositeImage = $(".imgBox2").attr("data-value");//身份证反面
 		var vehicleImage = $(".imgBox3").attr("data-value");//人车合影
 		var jszImage = $(".imgBox4").attr("data-value");//驾驶证正本
 		var jszCopyImage = $(".imgBox5").attr("data-value");//驾驶证副本
 		var xszImage = $(".imgBox6").attr("data-value");//行车本正本
 		var xszCopyImage = $(".imgBox7").attr("data-value");//行车本副本
 		
 		if(wholeautype == 2){
 			var workLicenseImage = '';
 			var workLicenseNumber = '';
 		}
		else {
			var workLicenseImage = $(".imgBox8").attr("data-value");//从业资格证
	 		var workLicenseNumber = $(".workLicenseNumber").val();//从业资格证号
		}
 		
        if(firstLicDate.length < 5) {
        	alert("请选择初领驾驶证日期");
        }
        else if(endLicDate.length < 5) {
        	alert("请选择驾驶证截止日期");
        }
        else if(carRegisterDate.length < 5) {
        	alert("车辆注册日期");
        }
        else if(vehicleModel == '请选择车辆品牌') {
 			alert("请输入首字母选择车辆品牌");
 		}
 		else if(new Date(firstLicDate.replace(/\-/g, "\/")) > new Date(endLicDate.replace(/\-/g, "\/"))) {
 			alert("驾驶证初领日期不能大于驾驶证截止日期");
 		}
 		else if(idCardPositiveImage == '') {
 			alert("请上传身份证正面图片");
 		}
 		else if(idCardOppositeImage == '') {
 			alert("请上传身份证反面图片");
 		}
 		else if(vehicleImage == '') {
 			alert("请上传人车合影图片");
 		}
 		else if(jszImage == '') {
 			alert("请上传驾驶证正本");
 		}
 		else if(jszCopyImage == '') {
 			alert("请上传驾驶证副本");
 		}
 		else if(xszImage == '') {
 			alert("请上传行车本正本");
 		}
 		else if(xszCopyImage == '') {
 			alert("请上传行车本副本");
 		}
 		else{
 			$.ajax({
 	 			type: 'POST',
 	 			url: ctx+'/driver/v1/dvadd',
 	 			dataType: 'json',
 	 			data: {
 	 				sex: driverSex,
 	 				idCard: driverIdCard,
 	 				jszFileNumber: licNo,
 	 				jszLssueDate: firstLicDate,
 	 				lisencePlate: driverCarNo,
 	 				permittedType: licType,
 	 				telPhone: driverTel,
 	 				trueName: driverName,
 	 				vehicleType: vehicleType,
 	 				vehicleModel: vehicleModel,
 	 				vehicleNumber: vehicleNo,
 	 				vehicleOwner: carOwnName,
 	 				xszLssueDate: carRegisterDate,
 	 				jszValidityPeriod: endLicDate,
 	 				idCardPositiveImage: idCardPositiveImage,
 	 				idCardOppositeImage: idCardOppositeImage,
 	 				vehicleImage: vehicleImage,
 	 				jszImage: jszImage,
 	 				jszCopyImage: jszCopyImage,
 	 				xszImage: xszImage,
 	 				xszCopyImage: xszCopyImage,
 	 				authType:authType,
 	 				vehicleColor:vehicleColor,
 	 				workLicenseImage: workLicenseImage,
 	 				workLicenseNumber: workLicenseNumber
 	 				
 	 			},
 	 			success: function(data) {
 	 				console.log(data);
 	 				if(data == 'success') {
 	 					alert("添加成功");
 	 					location.replace(location.href);
 	 				}
 	 			},
 	 			error:function(data) {
 	 	            console.log(data);
 	 	            if(typeof(data.responseJSON.message) != 'undefined') {
 	 	              alert(data.responseJSON.message);
 	 	            }
 	 	        }
 	 		});
 		}
 		
        console.log(111222);
    }
    
    
    //获取当前时间，格式YYYY-MM-DD
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
    
    
});